<template>
  <el-dialog
    center
    :title="dialogData.type === 'add' ? '新增奖品' : '编辑奖品'"
    :close-on-click-modal="false"
    :visible.sync="dialogData.isShow"
    width="30%"
  >
    <div class="form-box">
      <el-form
        ref="formData"
        :rules="rules"
        :model="formData"
        label-width="120px"
      >
        <el-form-item label="一级分类:" prop="classifyId">
          <el-select
            size="small"
            v-model="formData.classifyId"
            placeholder="请选择一级分类"
            @change="checkClassifId"
          >
            <el-option
              v-for="item in classifyList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="二级分类:" prop="secondaryClassifyId">
          <el-select
            size="small"
            v-model="formData.secondaryClassifyId"
            placeholder="请选择二级分类"
          >
            <el-option
              v-for="item in secondaryClassifyList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="奖品名称:" prop="name">
          <el-input
            type="text"
            placeholder="请输入奖品名称"
            v-model.trim="formData.name"
            maxlength="20"
            show-word-limit
          >
          </el-input>
        </el-form-item>
        <el-form-item label="兑换价:" prop="exchangeAmount">
          <el-input
            v-model.trim="formData.exchangeAmount"
            type="number"
            placeholder="请输入奖品兑换价"
          ></el-input>
        </el-form-item>
        <el-form-item class="min-margin" label="奖品图片" prop="img">
          <uploadSingImg
            :imgUrl="formData.img"
            accept=".jpg,.jpeg,.png"
            :maxSize="1"
            @getImgUrl="getPrizeImg"
            :disabled="false"
          >
            <template v-slot:imgInfo
              >支持jpg、png格式上传，最大不超过1M<br />实体建议尺寸143x143，卡卷建议286X184</template
            >
          </uploadSingImg>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="success" plain @click="dialogData.isShow = false"
        >取 消</el-button
      >
      <el-button type="success" @click="confirm('formData')">提交</el-button>
    </span>
  </el-dialog>
</template>
<script>
import uploadSingImg from '@common/uploadSingImg' // 上传单个图片公共组件
import {
  getClassify,
  getPrizeDetail,
  verifyPrizeName,
  addPrize,
  editPrize
} from '@/api/partner/prizes'
export default {
  props: ['dialogData', 'classifyList'],
  watch: {
    'formData.classifyId': {
      handler(newV) {
        if (this.dialogData.type === 'add') {
          this.formData.secondaryClassifyId = ''
        }
        getClassify({ id: newV }, (res) => {
          this.secondaryClassifyList = res.rows
        })
      },
      deep: true
    }
  },
  data() {
    var validatePrice = (rule, value, callback) => {
      var reg = /((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/
      if (value < 0 || !reg.test(value)) {
        callback(new Error('请输入大于等于0且精度保留两位小数的数值'))
      } else {
        callback()
      }
    }
    var validatePrizeName = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入奖品名称'))
      }
      verifyPrizeName(
        { prizeName: value, id: this.dialogData.id },
        () => {
          callback()
        },
        (error) => {
          callback(new Error(`${error.message}`))
        }
      )
    }
    return {
      secondaryClassifyList: [],
      formData: {
        classifyId: '',
        secondaryClassifyId: '',
        name: '',
        exchangeAmount: '',
        img: ''
      },
      rules: {
        classifyId: [
          { required: true, message: '请选择一级分类', trigger: 'change' }
        ],
        secondaryClassifyId: [
          { required: true, message: '请选择二级分类', trigger: 'change' }
        ],
        name: [
          { required: true, validator: validatePrizeName, trigger: 'blur' }
        ],
        exchangeAmount: [
          { required: true, validator: validatePrice, trigger: 'blur' }
        ],
        img: [
          { required: true, message: '至少上传一张图片', trigger: 'change' }
        ]
      }
    }
  },
  components: {
    uploadSingImg
  },
  mounted() {
    if (this.dialogData.type === 'edit') {
      getPrizeDetail(this.dialogData, (res) => {
        this.formData = res
      })
    }
  },
  methods: {
    /* 上传图片 */
    getPrizeImg(url) {
      this.formData.img = url
    },
    /* 重新选择一级清空二级 */
    checkClassifId() {
      this.formData.secondaryClassifyId = ''
    },
    /* 提交 */
    confirm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm('确认提交？', '确认提交', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            center: true
          })
            .then(() => {
              const { type } = this.dialogData
              if (type === 'add') {
                addPrize(this.formData, () => {
                  this.$emit('searchList')
                  this.dialogData.isShow = false
                })
              } else {
                editPrize(this.formData, () => {
                  this.$emit('searchList')
                  this.dialogData.isShow = false
                })
              }
            })
            .catch(() => {})
        }
      })
    }
  }
}
</script>
<style lang="less" scoped></style>
